import React from "react";
import { useAuth } from "context/authContext";
import { Button, Form, Input } from "antd";
import styled from "@emotion/styled";
import { useAsync } from "../hooks/useAsync";

export const RegisterScreen = ({
  onError,
}: {
  onError: (error: Error) => void;
}) => {
  const { register } = useAuth();
  const { run, isLoading } = useAsync(undefined, { throwOnError: true });
  const handleSubmit = ({
    confirmationPassword,
    ...values
  }: {
    username: string;
    password: string;
    confirmationPassword: string;
  }) => {
    if (confirmationPassword !== values.password) {
      onError(new Error("请确认两次输入密码相同"));
      return;
    }
    run(register(values)).catch(onError);
  };
  return (
    <Form onFinish={handleSubmit}>
      <Form.Item
        name="username"
        rules={[{ required: true, message: "请输入用户名" }]}
      >
        <Input type="text" id="username" placeholder="用户名" />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[{ required: true, message: "请输入密码" }]}
      >
        <Input type="password" id="password" placeholder="密码" />
      </Form.Item>
      <Form.Item
        name="confirmationPassword"
        rules={[{ required: true, message: "请确认密码" }]}
      >
        <Input
          type="password"
          id="confirmationPassword"
          placeholder="确认密码"
        />
      </Form.Item>
      <Form.Item>
        <LongButton htmlType="submit" type="primary" loading={isLoading}>
          注册
        </LongButton>
      </Form.Item>
    </Form>
  );
};

const LongButton = styled(Button)`
  width: 100%;
`;
